/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.commons.util.print;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.ArrayList;
import java.util.List;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.swing.JOptionPane;

import com.barcodelib.barcode.Linear;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.commons.util.Util;

/**
 * 说明： 条码打印
 * 
 * @Author：李智深
 * @Date：2012-05-11
 */
public class BarcodePrint extends Thread implements Printable {

	private List<TCommodity> commodityList;
	private String printName;

	public BarcodePrint(List<TCommodity> commodityList, String printName) {
		this.commodityList = commodityList;
		this.printName = printName;
	}

	/**
	 * * @param Graphic指明打印的图形环境 * @param
	 * PageFormat指明打印页格式（页面大小以点为计量单位，1点为1英寸的1/72，1英寸为25.4毫米。A4纸大致为595×842点） * @param
	 * pageIndex指明页号
	 **/
	@Override
	public int print(Graphics gra, PageFormat pf, int pageIndex)
			throws PrinterException {
		Graphics2D g2 = (Graphics2D) gra;
		g2.setColor(Color.BLACK);

		// 打印起点坐标
		double x = pf.getImageableX() + 15;
		double y = pf.getImageableY() + 10;
		switch (pageIndex) {
		case 0:
			int lineHeihth = 9;
			int xx = 0;
			int yy = 0;
			int row = 1;
			int barcodeY = 0;
			for (int i = 0; i < commodityList.size(); i++) {
				if (i % 2 != 0) {
					xx = 154;
				} else {
					xx = 0;
				}
				if (i != 0 && i % 2 == 0) {
					yy = 90 * row;
					barcodeY = 90 * row;
					row++;
				}
				TCommodity commodity = commodityList.get(i);
				// g2.draw(new RoundRectangle2D.Double(x-10+xx, y-10+yy, 142,
				// 85, 10, 10));//画边框圆弧
				g2.setFont(Util.TICKETFONT); // 设置字体
				g2.drawString("商品名称：" + commodity.getName(), (int) x + xx+9,
						lineHeihth * 1 + 5 + yy);// 商品编号
				g2.setFont(Util.TICKETFONT3); // 设置字体
				g2.drawString("现价：￥" + commodity.getDiscountPrice(), (int) x
						+ xx+9, lineHeihth * 2 + 5 + yy);// 是商品现价
				g2.setFont(Util.TICKETFONT); // 设置字体
				// g2.drawString("正品验证码："+commodity.getBarcode(), (int)x+xx,
				// lineHeihth*3+5+yy);//正品验证码（即条码编号）
				g2.setFont(Util.TICKETFONT4); // 设置字体
				// Image
				// im=SampleBitmapBarcodeWithBean.createCode39Bean("*"+commodity.getBarcode()+"*");
				// JBarcodeBean jBarcodeBean = new JBarcodeBean();
				// //条形码类型
				// jBarcodeBean.setCodeType(new Code128());
				// jBarcodeBean.setBarcodeHeight(200);
				// //在条形码下面显示文字
				// jBarcodeBean.setLabelPosition(JBarcodeBean.LABEL_BOTTOM);
				// //设置条形码的值
				// jBarcodeBean.setCode(commodity.getBarcode());
				// BufferedImage image = new BufferedImage(200,
				// 200,BufferedImage.TYPE_INT_RGB);
				// image = jBarcodeBean.draw(image);

				Linear barcode = new Linear();
				barcode.setType(Linear.CODE128);
				// barcode data to encode
				barcode.setData(commodity.getBarcode());
//				barcode.setTextFont(barcode.getTextFont().deriveFont(30));
				// unit of measure for X, Y, LeftMargin, RightMargin, TopMargin,
				// BottomMargin
				barcode.setUOM(Linear.UOM_PIXEL);
				// barcode module width in pixel
				barcode.setX(3f);
				// barcode module height in pixel
				barcode.setY(75f);

				barcode.setLeftMargin(0f);
				barcode.setRightMargin(0f);
				barcode.setTopMargin(0f);
				barcode.setBottomMargin(0f);
				// barcode image resolution in dpi
				barcode.setResolution(72);

				// disply human readable text under the barcode
				barcode.setShowText(true);
				// human reable text font style
				barcode.setTextFont(new Font("Arial", 0, 26));
				// ANGLE_0, ANGLE_90, ANGLE_180, ANGLE_270
				barcode.setRotate(Linear.ANGLE_0);

				try {
					// barcode.renderBarcode("c://itf14.gif");
					BufferedImage image = barcode.renderBarcode();
					g2.drawImage(image, (int) x + xx,
							lineHeihth * 3 + barcodeY, 125, 44, null);
				} catch (Exception e) {
					e.printStackTrace();
				}

				// BufferedImage image = new BufferedImage(200,
				// 200,BufferedImage.TYPE_INT_RGB);
				// g2.drawImage(new
				// ImageIcon("c://itf14.gif").getImage(),(int)x+xx,lineHeihth*3+barcodeY,125,44,null);
			}
			return PAGE_EXISTS;
		default:
			return NO_SUCH_PAGE;
		}
	}

	private void receiptsPrint() {
		Book book = new Book();
		PageFormat pf = new PageFormat();// 指明打印页格式（页面大小以点为计量单位，1点为1英寸的1/72，1英寸为25.4毫米。A4纸大致为595×842点）
		pf.setOrientation(PageFormat.PORTRAIT); // LANDSCAPE表示竖打;PORTRAIT表示横打;REVERSE_LANDSCAPE表示打印空白
		Paper p = new Paper();
		int row = 0;
		if (commodityList.size() % 2 == 0) {
			row = commodityList.size() / 2;
		} else {
			row = commodityList.size() / 2 + 1;
		}
		p.setSize(313, row * 100); // 纸张大小(590, 840)表示A4纸
		p.setImageableArea(0, 0, 313, row * 100); // A4(595 X
		pf.setPaper(p);
		book.append(this, pf);
		PrinterJob job = PrinterJob.getPrinterJob();
		job.setPageable(book);

		HashAttributeSet hs = new HashAttributeSet();
		hs.add(new PrinterName(printName, null));
		PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, hs);
		if (pss.length == 0) {
			JOptionPane.showMessageDialog(null, "无法找到打印机:" + printName);
			return;
		}
		try {

			// 可以用printDialog显示打印对话框，在用户确认后打印；也可以直接打印
			job.setPrintService(pss[0]);
			job.print();
		} catch (PrinterException e) {
			JOptionPane.showMessageDialog(null, "请确定已经开启打印服务！");
			// e.printStackTrace();
		}
	}

	public void run() {
		receiptsPrint();
	}

	public static void main(String[] args) {
		try {
			// 30112345000018

			TCommodity com = new TCommodity();
			com.setBarcode("123456789101155");
			com.setName("商品名称");
			com.setPrice(11.00);
			List<TCommodity> list = new ArrayList<TCommodity>();
			list.add(com);
			list.add(com);
			List<String> prints = Util.getAllPrinter();
			if (prints != null && prints.size() != 0) {
				new BarcodePrint(list, prints.get(0)).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Linear barcode = new Linear();
		// barcode.setType(Linear.ITF14);
		// // barcode data to encode
		// // should be 13 digits
		// barcode.setData("09999999999999");
		//
		// barcode.setBearerBar(Linear.BEARERBAR_FRAME);
		//
		// // wide bar width vs narrow bar width ratio
		// barcode.setN(3.0f);
		//
		// // unit of measure for X, Y, LeftMargin, RightMargin, TopMargin,
		// BottomMargin
		// barcode.setUOM(Linear.UOM_PIXEL);
		// // barcode module width in pixel
		// barcode.setX(3f);
		// // barcode module height in pixel
		// barcode.setY(75f);
		//
		// barcode.setLeftMargin(0f);
		// barcode.setRightMargin(0f);
		// barcode.setTopMargin(0f);
		// barcode.setBottomMargin(0f);
		// // barcode image resolution in dpi
		// barcode.setResolution(72);
		//
		// // disply human readable text under the barcode
		// barcode.setShowText(true);
		// // human reable text font style
		// barcode.setTextFont(new Font("Arial", 0, 12));
		// // ANGLE_0, ANGLE_90, ANGLE_180, ANGLE_270
		// barcode.setRotate(Linear.ANGLE_0);
		//
		// try {
		// barcode.renderBarcode("c://itf14.gif");
		// } catch (Exception e) {
		// // TODO Auto-generated catch block123456789123456

		// e.printStackTrace();
		// }123456789123456

		// Linear barcode = new Linear();
		// barcode.setType(Linear.CODE128);
		// // barcode data to encode
		// barcode.setData("123456789123456");
		//
		// // unit of measure for X, Y, LeftMargin, RightMargin, TopMargin,
		// BottomMargin
		// barcode.setUOM(Linear.UOM_PIXEL);
		// // barcode module width in pixel
		// barcode.setX(3f);
		// // barcode module height in pixel
		// barcode.setY(75f);
		//
		// barcode.setLeftMargin(0f);
		// barcode.setRightMargin(0f);
		// barcode.setTopMargin(0f);
		// barcode.setBottomMargin(0f);
		// // barcode image resolution in dpi
		// barcode.setResolution(72);
		//
		// // disply human readable text under the barcode
		// barcode.setShowText(true);
		// // human reable text font style
		// barcode.setTextFont(new Font("Arial", 0, 12));
		// // ANGLE_0, ANGLE_90, ANGLE_180, ANGLE_270
		// barcode.setRotate(Linear.ANGLE_0);
		//
		// try {
		// barcode.renderBarcode("c://code128.gif");
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

	}
}
